package Action.user;

import Bean.Log.UserLogEntity;
import Bean.UserinfoEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import tools.HibernateTools;
import tools.TimeTools;

import java.util.LinkedList;
import java.util.List;

public class LoginRecord extends ActionSupport {
    LinkedList<String[]> data;
    UserinfoEntity userinfoEntity;
    int userid;

    @Override
    public String execute() throws Exception {
        userid = (int)ActionContext.getContext().getSession().get("userid");
        data = new LinkedList<>();
        Session session = HibernateTools.getSession();
        List<UserLogEntity> userLogEntities = session.createQuery("from UserLogEntity where userId=?  order by timestamp desc ")
                .setParameter(0, userid)
//                .setParameter(1, Setting.UserLog_flag_UserLogin)
//                .setParameter(2, Setting.UserLog_flag_UserLogout)
                .getResultList();
        for (UserLogEntity userLogEntity : userLogEntities) {
            int day= 0;
            String day_s;
            try {
                day = -TimeTools.Remainder_days(userLogEntity.getTimestamp());
                if (day==0)
                {
                    day_s="今天";
                }else if (day==1){
                    day_s="昨天";
                }
                else {
                    day_s=""+day+"天前";
                }
            } catch (Exception e) {
               day_s="未知";
            }


            //时间,多久前,事件,ip地址,地点
            if (userLogEntity.getTimestamp()!=null)//数据不完整
            data.add(new String[]{TimeTools.timeStamp2Date(userLogEntity.getTimestamp(),null),userLogEntity.getFlag(),day_s,userLogEntity.getIpAddress(),"未知"});
        }

        //最后一次登录记录从用户信息表中取出
        userinfoEntity=session.get(UserinfoEntity.class, userid);
        HibernateTools.commit(session);
        return SUCCESS;
    }

    public LinkedList<String[]> getData() {
        return data;
    }

    public void setData(LinkedList<String[]> data) {
        this.data = data;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public UserinfoEntity getUserinfoEntity() {
        return userinfoEntity;
    }

    public void setUserinfoEntity(UserinfoEntity userinfoEntity) {
        this.userinfoEntity = userinfoEntity;
    }
}
